#!./common/bats/bin/bats 
# -*-sh-*-

source ./common/test_helper_functions.bash || exit 1
source ./common/functions                  || exit 1

if [ -s ./TEST_ENV ];then
    source ./TEST_ENV
fi

PKG=R_BASE
testname=R_base
module=R_base
rpm=R_base${DELIM}

# Query local compiler family
check_compiler_family CC CXX FC

@test "[$testname] Verify $module module is loaded and matches rpm version ($LMOD_FAMILY_COMPILER)" {
    module list $module | grep "1) $module" >& .cmd_output || exit 1
    run grep $module .cmd_output 
    assert_success
    
}

@test "[$testname] Verify ${PKG}_DIR is defined and exists ($LMOD_FAMILY_COMPILER)" {
    DIR=${PKG}_DIR
    if [ -z ${!DIR} ];then
        flunk "${PKG}_DIR directory not defined"
    fi
    
    if [ ! -d ${!DIR} || -z "${!DIR}" ];then
        flunk "directory ${!DIR} does not exist"
    fi 
}

@test "[$testname] Verify availability of $module executable -> R ($LMOD_FAMILY_COMPILER)" {
    run which R
    assert_success
}


@test "[$testname] Verify availability of $module executable -> Rscript ($LMOD_FAMILY_COMPILER)" {
    run which Rscript
    assert_success
}

# --------------
# SHARE Tests
# --------------

@test "[$testname] Verify module ${PKG}_SHARE is defined and exists ($LMOD_FAMILY_COMPILER)" {
    SHARE=${PKG}_SHARE

    if [ -z ${!SHARE} ];then
        flunk "${PKG}_SHARE directory not defined"
    fi
    
    if [ ! -d ${!SHARE} || -z "${!SHARE}" ];then
        flunk "directory ${!SHARE} does not exist"
    fi 
}


# Execution Test(s)

@test "[$testname] Running bench.R test" {

    run Rscript ./bench.R
    assert_success
}

@test "[$testname] Verify ability to compile C code for R and execute" {

    # Compile C code
    rm -f foo.so 

    run R CMD SHLIB foo.c
    assert_success
    run ls -l foo.so
    assert_success

    # Verify execution
    run Rscript ./test_foo.R
    assert_success
}

